package com.example.taluo.common;

import com.example.taluo.config.CurrentUser;
import com.example.taluo.security.TokenProvider;
import com.example.taluo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/*** @Author supersaiya
 * @Description TODO

 * @Date 2025/2/15 23:38

 * @Version 1.0*/

// 创建参数解析器
@Component
public class CurrentUserResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private TokenProvider tokenProvider;
    @Autowired
    private UserService userService;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(CurrentUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        String authHeader = webRequest.getHeader("Authorization");
        System.out.println("Authorization header: " + authHeader);

        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            System.out.println("Invalid Authorization header format");
            return null;
        }

        String token = authHeader.substring(7); // 去掉 "Bearer " 前缀
        System.out.println("Parsed token: " + token);

        String userId = tokenProvider.getUserIdFromToken(token);
        System.out.println("Parsed userId: " + userId);

        if (userId == null) {
            System.out.println("UserId is null, token might be invalid");
            return null;
        }

        // 使用用户 ID 获取用户对象
        return userService.getUserById(Integer.parseInt(userId));
    }
}